<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button
            type="primary"
            size="small"
            @click="addFn(1, '0')"
          >添加权限</el-button>
        </div>

        <el-table border :data="PerList" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template v-slot="scoped">
              <!-- 只有页面级别的节点才有添加功能 -->
              <el-button
                v-if="scoped.row.type === 1"
                type="text"
                @click="addFn(2, scoped.row.id)"
              >添加</el-button>
              <el-button
                type="text"
                @click="editFn(scoped.row.id)"
              >编辑</el-button>
              <el-button type="text" @click="delFn(scoped.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 放置一个弹层 用来编辑新增节点 -->
        <el-dialog
          :title="isEdit ? '编辑权限点' : '新增权限点'"
          :visible="showDialog"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          @close="btnCancel"
        >
          <!-- 表单 -->
          <el-form
            ref="perForm"
            :model="formData"
            :rules="rules"
            label-width="120px"
          >
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="formData.name" style="width: 90%" />
            </el-form-item>
            <el-form-item label="权限标识" prop="code">
              <el-input v-model="formData.code" style="width: 90%" />
            </el-form-item>
            <el-form-item label="权限描述">
              <el-input v-model="formData.description" style="width: 90%" />
            </el-form-item>
            <el-form-item label="开启">
              <el-switch
                v-model="formData.enVisible"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" type="primary" @click="submitFn">{{
                isEdit ? "修改" : "确定"
              }}</el-button>
              <el-button size="small" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import {
  addPermission,
  delPermission,
  getPermissionDetail,
  getPermissionList,
  updatePermission
} from '@/api/permission'
import { tranListToTreeData } from '@/utils'
export default {
  data() {
    const validName = (rule, value, callback) => {
      // 找到pid与当前pid相同的,整合为一个数组
      // 再将兄弟节点的name组成数组
      // 如果当前数组包含value,那么就重复了,将错误返回出来
      // 如果是编辑状态,需要找到当前的兄弟节点,并且排除自己
      (this.isEdit
        ? this.orginList.filter(
          (item) =>
            item.pid === this.formData.pid && item.id !== this.formData.id
        )
        : this.orginList.filter((item) => item.pid === this.formData.pid)
      )
        .map((item) => item.name.trim())
        .includes(value)
        ? callback(new Error(`权限名称${value}已存在`))
        : callback()
    }
    // code的验证
    const validCode = (rule, value, callback) => {
      // 所有的code都不能重复,
      // 如果是编辑模式,需要去除自己
      // map与filter的区别,map可以将数组按特定的要求,返回一个新数组,filter可以将符合条件的值直接添加到新数组内
      (this.isEdit
        ? this.orginList.filter((item) => item.id !== this.formData.id)
        : this.orginList
      )
        .map((item) => item.code)
        .includes(value)
        ? callback(new Error(`权限标识${value}已存在`))
        : callback()
    }
    return {
      PerList: [], // 树形数据
      showDialog: false, // 是否显示弹层
      isEdit: false,
      orginList: [], // 用于验证的精简数据
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 调用获取权限列表的方法
    this.getPerList()
  },
  methods: {
    // 获取权限列表
    async getPerList() {
      const res = await getPermissionList()
      // 将数据转为树形格式
      this.PerList = tranListToTreeData(res.data)
      // 精简数据,用于验证
      this.orginList = res.data.map((item) => ({
        name: item.name,
        id: item.id,
        code: item.code,
        pid: item.pid
      }))
    },
    // 点击添加按钮触发
    addFn(type, pid) {
      this.formData.type = type
      this.formData.pid = pid
      this.showDialog = true
      // isedit
      this.isEdit = false
    },
    // 点击编辑按钮触发
    async editFn(id) {
      // 调用接口,获取详情
      const res = await getPermissionDetail(id)
      this.formData = res.data
      // 打开弹框
      this.showDialog = true
      // // isedit
      this.isEdit = true
    },
    // 点击删除
    async delFn(id) {
      const res = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (res === 'cancel') return this.$message('已取消删除')
      const delRes = await delPermission(id)
      this.$message.success(delRes.message)
      this.getPerList()
    },
    // 点击取消关闭
    btnCancel() {
      this.showDialog = false
      // 关闭后初始化
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      // resetFields只能初始化有验证规则的部分表单
      this.$refs.perForm.resetFields()
    },
    // 点击确定按钮
    submitFn() {
      this.$refs.perForm.validate(async(valid) => {
        // 兜底验证
        if (!valid) return
        // 这里增加三元判断
        const res = this.isEdit
          ? await updatePermission(this.formData)
          : await addPermission(this.formData)
        // 统一处理请求获得的结果
        this.$message.success(res.message)
        this.showDialog = false
        this.getPerList() // 重新渲染
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
